package cn.vc.shop.service;

import cn.vc.shop.entity.dto.ShopDto;
import cn.vc.shop.entity.po.Shop;
import cn.vc.shop.entity.po.ShoppingCart;
import cn.vc.shop.mapper.ShopMapper;
import cn.vc.shop.mapper.ShoppingCartMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
public class ShopService extends ServiceImpl<ShopMapper, Shop> {
    private final ShopMapper shopMapper;

    public ShopService(ShopMapper shopMapper) {
        this.shopMapper = shopMapper;
    }



    public boolean signOut(Long id) {
        return shopMapper.deleteById(id)==1;
    }


    /**
     * 通过用户ID查询商铺
     * @param userId
     * @return
     */
    public ShopDto selectByUserId(Long userId) {
        LambdaQueryWrapper<Shop> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Shop::getUserId, userId);
        Shop shop = shopMapper.selectOne(lqw);
        if (shop==null) return null;
        ShopDto shopDto = new ShopDto();
        BeanUtils.copyProperties(shop,shopDto);
        return shopDto;
    }



    public boolean updateById(Shop shop) {
        return shopMapper.updateById(shop)==1;
    }
    /**
     * <h2>关注</h2>
     * @param id
     * @param mark
     * @return
     */
    public Boolean follow(Long id) {
        Shop shop = shopMapper.selectById(id);
        shop.setPeopleNum(shop.getPeopleNum()+1);
        return shopMapper.updateById(shop)==1;
    }
    /**
     * <h2>取关</h2>
     * @param id
     * @param mark
     * @return
     */
    public Boolean noFollow(Long id) {
        Shop shop = shopMapper.selectById(id);
        shop.setPeopleNum(shop.getPeopleNum()-1);
        return shopMapper.updateById(shop)==1;
    }
    /**
     * <h2>评分</h2>
     * @param id
     * @param mark
     * @return
     */
    public Double marking(Long id, Integer mark) {
        if (mark <= 0) return 0D;
        Shop shop = shopMapper.selectById(id);
        Double d = shop.getMark() * shop.getMarkNum();//获取全部人数的总评分
        d += mark;//加上新的评分
        shop.setMarkNum(shop.getMarkNum()+1);//加一个人数
        shop.setMark(d / shop.getMarkNum());//重新平均评分并赋值
        shopMapper.updateById(shop);
        return shop.getMark();
    }
    /**
     * <h2>取消评分</h2>
     * @param id
     * @param mark
     * @return
     */
    public Double noMarking(Long id, Integer mark) {
        if (mark <= 0) return 0D;
        Shop shop = shopMapper.selectById(id);
        Double d = shop.getMark() * shop.getMarkNum();//获取全部人数的总评分
        d -= mark;//减去旧的评分
        shop.setMarkNum(shop.getMarkNum()-1);//减一个人数
        shop.setMark(d / shop.getMarkNum());//重新平均评分并赋值
        shopMapper.updateById(shop);
        return shop.getMark();
    }
}
